package com.jiang.spring_security_singleboot.config;

import com.jiang.spring_security_singleboot.service.IUserService;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.annotation.Resource;

/**
 * @中软华腾软件系统有限公司,未经授权不得擅自传播
 * @类描述:
 * @类名称:SpringSecurityConfig
 * @作者: 蒋正午
 * @编辑时间: 2021/4/26 21:07
 * @版本: 1.0
 */
@Configuration
// 如果要支持Security要注解@EnableWebSecurity
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    // 暂时内存写死用户名与密码
//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication().withUser("user").password("{noop}"+"123")
//                .roles("USER"); // 使用springboot配置记住不用加ROLE，默认的角色就是ROLE_自己配置的名字
//    }

    @Resource
    private IUserService userService;
    // 引入加密器
    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    // 这里配置成读取数据库的用户名与密码验证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder);
    }
    // 暂时没有配置什么
    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

    // 配置拦截路径
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 使用springboot配置记住不用加ROLE，默认的角色就是ROLE_自己配置的名字
        http.authorizeRequests().antMatchers("/login.jsp","/login","/css/**","/img/**","/plugins/**","/logout").permitAll()
                .antMatchers("/**").hasAnyRole("USER").anyRequest().authenticated().and()
                .formLogin().loginPage("/login.jsp").loginProcessingUrl("/login").successForwardUrl("/index.jsp")
                .failureForwardUrl("/failer.jsp").and().logout().logoutUrl("/logout").invalidateHttpSession(true).and().csrf().disable(); // invalidateHttpSession不使用session因为分布式最好无状态

    }
}
